package com.web.oa.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.PageInfo;
import com.web.oa.pojo.*;
import com.web.oa.service.EmployeeService;
import com.web.oa.service.SysService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private SysService sysService;




    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model){
            String errorName = (String) request.getAttribute("shiroLoginFailure");

            if (errorName != null) {
                if("errorCheckCode".equals(errorName)) {
                    model.addAttribute("errorMsg", "验证码不正确");
                }else if (UnknownAccountException.class.getName().equals(errorName)) {
                    model.addAttribute("errorMsg", "用户名不存在！");
                } else if (IncorrectCredentialsException.class.getName().equals(errorName)) {
                    model.addAttribute("errorMsg", "密码不正确！");
                }  else {
                    model.addAttribute("errorMsg", "未知错误！");
                }
            }
        return "login";
    }

    //角色列表
    @RequestMapping("/findRoles")
    public String findRoles(Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();

        PageInfo<SysRole> pageInfo = sysService.findAllRoles(pageNum);
        List<MenuTree> allMenuTree = sysService.findAllMenuTrees();

        model.addAttribute("activeEmployee",activeEmployee);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("allMenuTree",allMenuTree);

        return "permissionlist";
    }


    //转成json数据
    @RequestMapping("/editPermissionListByRoleId")
    @ResponseBody
    public List<SysPermission> editPermissionListByRoleId(String roleId){
        return sysService.findPermissionListByRoleId(roleId);
    }

    //更新（roleId从隐藏域传入）
    @RequestMapping("/updateRoleAndPermission")
    public String updateRoleAndPermission(String roleId,int[] permissionIds){
        sysService.updateRoleAndPermissionByRoleId(roleId,permissionIds);
        return "redirect:/findRoles";
    }

    //用户列表（包括角色分配、上级主管等）
    @RequestMapping("/findUserList")
    public String findUserList(Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        List<SysRole> roles = sysService.findAllRoles();
        PageInfo<Employee> pageInfo = employeeService.findAllUserAndRole(pageNum);
        model.addAttribute("roles",roles);
        model.addAttribute("pageInfo",pageInfo);
        return "userlist";
    }

    //重新分配角色
    @RequestMapping("/assignRole")
    @ResponseBody
    public Map<String,String> assignRole(String roleId,String userId){
        Map<String,String> map = new HashMap<>();
        try {
            employeeService.updateEmployeeRole(roleId,userId);
            map.put("msg","角色分配成功");
        } catch (Exception e){
            map.put("msg","角色分配失败");
        }
        return map;
    }

    //根据用户名 查看用户权限
    @RequestMapping("/viewPermissionByUser")
    @ResponseBody
    public SysRole viewPermissionByUser(String userName){
        return sysService.findRoleAndPermissionListByUserName(userName);
    }

    //增加用户 待完善
    @RequestMapping("/saveUser")
    public String saveUser(Employee employee){
        employeeService.addEmployee(employee);
        return "redirect:/findUserList";
    }

    @RequestMapping("/toAddRole")
    public String toAddRole(Model model){
        List<MenuTree> menuTree = sysService.findMenuTree();
        List<SysPermission> menus = sysService.findAllMenu();
        List<SysRole> list = sysService.findRoleAndPermissionList();

        model.addAttribute("menuTree",menuTree);
        model.addAttribute("menus",menus);
        model.addAttribute("roleAndPermissionList",list);

        return "rolelist";
    }

    //增加
    @RequestMapping("/saveRoleAndPermissions")
    public String saveRoleAndPermissions(SysRole role,int[] permissionIds) {
        role.setId(UUID.randomUUID().toString());
        role.setAvailable("1");
        sysService.addRoleAndPermissions(role, permissionIds);

        return "redirect:/toAddRole";
    }

    @RequestMapping("/saveSubmitPermission")
    public String saveSubmitPermission(SysPermission permission) {
/*        if (permission.getAvailable() == null) {
            permission.setAvailable("0");
        }*/
        sysService.addSysPermission(permission);
        return "redirect:/toAddRole";
    }

    @RequestMapping("/permission_delete")
    public String permission_delete(String id){
        employeeService.deleteRoleByRoleId(id);
        return "redirect:/findRoles";
    }
}
